package com.lun.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lun.domain.dto.PageDTO;
import com.lun.domain.po.Address;
import com.lun.domain.po.User;
import com.lun.domain.query.UserQuery;
import com.lun.domain.vo.AddressVO;
import com.lun.domain.vo.UserVO;
import com.lun.enums.UserStatus;
import com.lun.mapper.UserMapper;
import com.lun.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * ClassName: UserServiceImpl
 * Description:
 *
 * @Author wyl
 * @Create 2024/5/18 16:08
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

//    public void deductBalance(Long id, Integer money) {
//        // 1.查询用户
//        User user = getById(id);
//        // 2.判断用户状态
//        if (user == null || user.getStatus() == 2) {
//            throw new RuntimeException("用户状态异常");
//        }
//        // 3.判断用户余额
//        if (user.getBalance() < money) {
//            throw new RuntimeException("用户余额不足");
//        }
//        // 4.扣减余额
//        baseMapper.deductMoneyById(id, money);
//    }

    @Override
    @Transactional
    public void deductBalance(Long id, Integer money) {
        // 1.查询用户
        User user = getById(id);
        // 2.校验用户状态
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常！");
        }
        // 3.校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
        // 4.扣减余额 update tb_user set balance = balance - ?
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance) // 更新余额
                .set(remainBalance == 0, User::getStatus, 2) // 动态判断，是否更新status
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁 (判断当得到的余额 与 下面的余额一样时执行)
                .update();
    }

    @Override
    public UserVO queryUserAndAddressById(Long userId) {
        //1.查询用户
        User user = getById(userId);
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }
        //2。查询地址  db静态工具 无需注入service 防止service注入依赖循环
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, userId).list();
        //3.封装vo
        //3.1 转user 的po为vo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //3.2 转地址vo
        if (CollUtil.isNotEmpty(addresses)) {
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
//1.查询用户
        List<User> users = listByIds(ids);

        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        //2。查询地址
        //2.1 获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //2.1根据用户id集合查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        //2.3 转换地址vo
        List<AddressVO> addressVOSList = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.4 梳理地址集合，分类整理 相同用户的放到一个集合中
        Map<Long, List<AddressVO>> addressMap = new HashMap<>();
        if (CollUtil.isNotEmpty(addressVOSList)) {
            addressMap = addressVOSList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));

        }

        //3.转vo返回
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
            //3.1 转换user的po为vo
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            list.add(vo);
            //3.2 转换地址vo
            vo.setAddresses(addressMap.get(user.getId()));
        }
        return list;
    }

//    分类查询
//    public PageDTO<UserVO> queryUserPage(UserQuery query) {
//
//        String name = query.getName();
//        Integer status = query.getStatus();
//        //1.构建分页条件
//        //1。1 分页条件
//        Page<User> page = Page.of(query.getPageNo(), query.getPageSize());
//        //1.2 排序条件
//        if (StrUtil.isNotBlank(query.getSortBy())) {
//            //不为空
//            page.addOrder(new OrderItem(query.getSortBy(), query.getIsAsc()));
//        } else {
//            //为空，默认根据更新时间排序
//            page.addOrder(new OrderItem("update_time", false));
//        }
//        //2.分页查询
//        Page<User> p = lambdaQuery().like(name != null, User::getUsername, name)
//                .eq(status != null, User::getStatus, status)
//                .page(page);
//        //3.封装vo结果
//        //user 转为 vo
//        PageDTO<UserVO> dto = new PageDTO<>();
//        dto.setTotal(p.getTotal());
//        dto.setPages(p.getPages());
//        //当前页数据
//        List<User> records = p.getRecords();
//        if (CollUtil.isEmpty(records)) {
//            dto.setList(Collections.emptyList());
//            return dto;
//        }
//        //拷贝user的vo
//        dto.setList(BeanUtil.copyToList(records, UserVO.class));
//        //4.返回
//        return dto;
//    }

    /**
     * 通用工具类分页查询
     * @param query
     * @return
     */
    public PageDTO<UserVO> queryUserPage(UserQuery query) {

        String name = query.getName();
        Integer status = query.getStatus();
        //1.构建分页条件
        Page<User> page = query.toMpPageDefaultSortByUpdateTimeDesc();

        //2.分页查询
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);
        //3.封装vo结果

//        return PageDTO.of(p,UserVO.class);
        return PageDTO.of(p,user -> {
            //1.拷贝基础属性
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            //2.处理特殊字段  隐藏名字后两位
            vo.setUsername(vo.getUsername().substring(0,vo.getUsername().length()-2)+"**");
            return vo;
        });
    }


}

